package com.hsy.swu

import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.animation.DecelerateInterpolator
import androidx.appcompat.widget.AppCompatImageView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.hsy.swu.databinding.ActivityHomeBinding
import com.hsy.swu.databinding.DialogWelcomeBinding
import com.hsy.swu.home.HomeFragment
import com.hsy.swu.hsyutils.HsyActivity
import com.hsy.swu.hsyutils.HsyDialog
import com.hsy.swu.hsyutils.MActivityUtil
import com.hsy.swu.other.OtherFragment
import com.hsy.swu.spider.SwuSpiderHelper
import com.hsy.swu.version.Updater
import com.hsy.swueasspider.utils.SwuEasCookieUtils
import com.hsy.swueasspider.utils.SwuEasSpiderUtils
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlin.math.abs

class HomeActivity : HsyActivity<ActivityHomeBinding, HomeViewModel>() {
    var onBackPressedHomeFragmentListener: (() -> Unit)? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        SwuEasCookieUtils.readCookie(this)

        /*HomeFragment.isChecked = spRead(HomeFragment.IS_CHECKED)
        if (HomeFragment.isChecked.isEmpty()) HomeFragment.isChecked = "0"
        mBinding.root.postDelayed({
            if (HomeFragment.isChecked == "1") {
                startService(Intent(this, SwuSpiderService::class.java))
            }
            if (LeanCloudHelper.tempIsNeedShowSubmitDialog) {
                LeanCloudHelper.getInstance()?.showSubmitDialog(lifecycleScope)
            }
        }, 1000)*/

        intent.getBooleanExtra("isButtonLogin", false).let { isButtonLogin ->
            if (isButtonLogin) {
                MActivityUtil.showToast("登录成功")
                object : HsyDialog<DialogWelcomeBinding>(this, { dialogBinding, dialog ->
                    dialogBinding.btnRefresh.setOnClickListener {
                        dialog.dismiss()
                        SwuSpiderHelper.startSwuSpiderService(this)
                    }
                }, true) {}.show()
            }
        }

        MyConfig.update()

        val page1Fragment = HomeFragment()
//        val page2Fragment =
        val page3Fragment = OtherFragment()
        setBottomNavBarBtnClickListener { page ->
            when (page) {
                1 -> supportFragmentManager.navigateTo(
                    mBinding.homeFragmentContainerView.id,
                    page1Fragment
                )

//                2 -> supportFragmentManager.navigateTo(
//                    mBinding.homeFragmentContainerView.id,
//                    page2Fragment
//                )

                3 -> supportFragmentManager.navigateTo(
                    mBinding.homeFragmentContainerView.id,
                    page3Fragment
                )
            }
        }
        select(1)
        supportFragmentManager.navigateTo(mBinding.homeFragmentContainerView.id, page1Fragment)

        Updater(this).apply {
            if (checkIsNeedUpdate()) {
                showUpdateDialog(true)
            }
        }

        startCheckEasConnectionStatus()
        setEasConnectionBarTouchEventListener()
    }

    override fun onBackPressed() {
        if (onBackPressedHomeFragmentListener == null) {
            super.onBackPressed()
        } else {
            onBackPressedHomeFragmentListener!!.invoke()
        }
    }

    private fun setBottomNavBarBtnClickListener(onPageChangeTo: (Int) -> Unit) {
        mBinding.apply {
            btnPage1.setOnClickListener {
                select(1)
                onPageChangeTo(1)
            }
            btnPage2.setOnClickListener {
                select(2)
                onPageChangeTo(2)
            }
            btnPage3.setOnClickListener {
                select(3)
                onPageChangeTo(3)
            }
        }
    }

    private fun select(page: Int) {
        when (page) {
            1 -> mBinding.apply {
                btnPage1.onSelected()
                btnPage2.unSelected()
                btnPage3.unSelected()
            }

            2 -> mBinding.apply {
                btnPage1.unSelected()
                btnPage2.onSelected()
                btnPage3.unSelected()
            }

            3 -> mBinding.apply {
                btnPage1.unSelected()
                btnPage2.unSelected()
                btnPage3.onSelected()
            }
        }
    }

    private fun View.onSelected() {
        (this as AppCompatImageView).imageTintList = null
        animate()
            .scaleX(0.8f)
            .scaleY(0.8f)
            .setDuration(100)
            .withEndAction {
                animate()
                    .scaleX(1f)
                    .scaleY(1f)
                    .setDuration(100)
                    .start()
            }
            .start()
    }

    private fun View.unSelected() {
        (this as AppCompatImageView).imageTintList =
            ColorStateList.valueOf(resources.getColor(R.color.lightGray))
    }

    private fun FragmentManager.navigateTo(fragmentContainerId: Int, fragment: Fragment) {
        this.beginTransaction()
            .replace(fragmentContainerId, fragment)
            .commit()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun setEasConnectionBarTouchEventListener() {
        var curY = 0f
        var isClick = true
        mBinding.llEasConnectionStatus.setOnTouchListener { v, event ->
            val theTop = mBinding.root.height * 0.1f
            val theBottom = mBinding.root.height * 0.9f
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    curY = v.y
                    isClick = true
                }

                MotionEvent.ACTION_MOVE -> {
                    v.x += event.x - v.width / 2

                    if (v.y in theTop..theBottom) {
                        if (abs(v.y - curY) > 0) {
                            isClick = false
                        }
                        v.y += event.y - v.height / 2
                    }
                }

                MotionEvent.ACTION_UP -> {
                    if (isClick) {
                    }
                    if (v.y < theTop) {
                        v.y = theTop * 1.1f
                    } else if (v.y > theBottom) {
                        v.y = theBottom * 0.98f
                    }
                    v.animate()
                        .translationX(0f)
                        .setDuration(500)
                        .setInterpolator(DecelerateInterpolator())
                        .start()
                }
            }
            return@setOnTouchListener true
        }
    }

    private var isEasConnected = false

    private fun changeConnectionStatus(isConnected: Boolean) {
        if (isEasConnected == isConnected) return
        isEasConnected = isConnected
        mBinding.root.post {
            mBinding.apply {
                if (isEasConnected) {
                    lottieStatus.setAnimation(R.raw.lottie_eas_connected)
                    tvStatus.text = "教务系统\n已连接"
                    tvStatus.setTextColor(getColor(R.color.eas_connected_green))
                } else {
                    lottieStatus.setAnimation(R.raw.lottie_eas_disconnected)
                    tvStatus.text = "教务系统\n未连接"
                    tvStatus.setTextColor(getColor(R.color.eas_disconnected_red))
                }
                lottieStatus.apply {
                    speed = 3.0f
                    repeatCount = 10000
                    playAnimation()
                }
            }
        }
    }

    private fun startCheckEasConnectionStatus() {
        val executors = Executors.newScheduledThreadPool(1)
        val checkEasStatusTask = Runnable {
            changeConnectionStatus(SwuEasSpiderUtils.isCookieUsable())
        }
        executors.scheduleWithFixedDelay(checkEasStatusTask, 0, 5, TimeUnit.SECONDS)
    }
}